<template>
	<view>
		<view v-if="$validatenull(deviceData)">
			<cust-empty desc="暂无车辆,请前往绑定!" btnText="前往绑定" :showDefaultBtn="true"
				@clickBtn="$navigateTo('/pagesMy/views/addDevice')">
			</cust-empty>
		</view>
		<view v-else>
			<view class="p30">
				<view class="flex-between">
					<text class="f36 bold">{{deviceData.nickName}}</text>
					<view class="flex-align-center" v-if="!$validatenull(weather.city)">
						<text class="f24 mr10">{{weather.city}} {{weather.district}} {{weather.textDay}}</text>
						<u-icon :name="weather.icon" :isShowIcon="false" customPrefix="iconfontbike iconbike"
							:color="weather.color"></u-icon>
					</view>
				</view>
				<view class="flex-row mt20">
					<view class="flex-align-center">
						<u-icon name="lanya" :color="isConnected?'#0099CC':'#999999'" size="12" :isShowIcon="false"
							customPrefix="iconfontbike iconbike"></u-icon>
						<text class="f24 ml4">{{isConnected?'已连接':'未连接'}}</text>
					</view>
					<view class="flex-align-center ml20">
						<u-icon name="shandian" :color="indexDataPoint.keyStatus == 1 ? '#0099CC' : '#999999'" size="12"
							:isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
						<text class="f24 ml4">{{indexDataPoint.keyStatus == 1 ? '已通电' : '未通电'}}</text>
					</view>
					<view class="flex-align-center ml20">
						<u-icon name="yunhangzhong" :color="indexDataPoint.engineStatus == 1 ? '#0099CC' : '#999999'"
							size="12" :isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
						<text class="f24 ml4">{{indexDataPoint.engineStatus == 1 ? '运行中' : '未运行'}}</text>
					</view>
					<view class="flex-align-center ml20">
						<u-icon name="cheliangzaixian" :color="indexDataPoint.lastUpFlag == 0 ? '#0099CC' : '#999999'"
							size="12" :isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
						<!-- lastUpFlag     是否超过最后上报时间 0=否 1=是超过上报时间，则车辆离线 （超过情况下认为车辆不在线） -->
						<text class="f24 ml4">{{indexDataPoint.lastUpFlag == 0 ? '在线中' : '离线中'}}</text>
					</view>
					<view class="flex-align-center ml20">
						<u-icon :name="indexDataPoint.carStatus == 2 ? 'yunxukaisuo1':'jinzhikaisuo1'"
							:color="indexDataPoint.carStatus == 2 ? '#0099CC' : '#EC1010'" size="11" :isShowIcon="false"
							customPrefix="iconfontbike iconbike"></u-icon>
						<text class="f24 ml4">{{indexDataPoint.carStatus == 2 ? '允许启动' : '禁止启动'}}</text>
					</view>
				</view>
			</view>
			<view class="pl30 flex-between">
				<view>
					<view class="flex-align-center">
						<text class="f30 c-desc mr10">续航里程</text>
						<u-icon name="yiwen" color="#666666" size="18" :isShowIcon="false"
							customPrefix="iconfontbike iconbike" @click="$showToast('续航里程为系统预估')"></u-icon>
					</view>
					<view class="flex-row baseline mt10">
						<view class="mr10" style="font-size: 20px;" v-if="enduranceMileage == '-'">-
						</view>
						<view class="mr10 f90 impact" v-else>
							<text style="color:#FD8C05" v-if="parseInt(indexDataPoint.surplusOil)<=12">
								{{lt}}
							</text>
							<text v-else>
								{{setNumerRound(enduranceMileage ,[10,450],0)}}
							</text>

						</view>
						<view class="f36 bold dinbold">km</view>
					</view>
					<view class="flex-row mt20" style="width: 360upx;">
						<view class="flex-align-center bg-white ptb4lr8" style="width: 200upx;">
							<u-icon name="youliang"
								:color="toFormatVal(indexDataPoint.surplusOil,[0,100],0)<=12?'#FD8C05':'#0EE306'"
								size="12" :isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
							<text class="f20 ml10">
								<text v-if="parseInt(indexDataPoint.surplusOil)<=12">
									油量低
								</text>
								<text v-else>
									{{toFormatVal(indexDataPoint.surplusOil,[0,100],0)}}%
								</text>
							</text>
						</view>
						<view class="flex-align-center bg-white ml20 ptb4lr8" style="width: 200upx;">
							<u-icon name="dianya"
								:color="toFormatVal(indexDataPoint.insideVoltage,[6,16],1)<12?'#FD8C05':'#0EE306'"
								size="12" :isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
							<text class="f20 ml10">{{toFormatVal(indexDataPoint.insideVoltage,[6,16],1)}}V</text>
						</view>
					</view>
					<view class="flex-row mt20" style="width: 360upx;">
						<view class="flex-align-center bg-white ptb4lr8" style="width: 200upx;">
							<u-icon name="taiya"
								:color="toFormatVal(indexDataPoint.carFrontTirePressure,[0,3.5],1)<1.8?'#FD8C05':'#0EE306'"
								size="12" :isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
							<text class="f20 ml10">FR {{toFormatVal(indexDataPoint.carFrontTirePressure,[0,3.5],1)}}bar</text>
						</view>
						<view class="flex-align-center bg-white ml20 ptb4lr8" style="width: 200upx;">
							<u-icon name="taiya"
								:color="toFormatVal(indexDataPoint.carRearTirePressure,[0,3.5],1)<1.8?'#FD8C05':'#0EE306'"
								size="12" :isShowIcon="false" customPrefix="iconfontbike iconbike"></u-icon>
							<text class="f20 ml10">RR {{toFormatVal(indexDataPoint.carRearTirePressure,[0,3.5],1)}}bar</text>
						</view>
					</view>
				</view>
				<view class="ml10 hidden" style="width:368upx;">
					<image :src="deviceData.carPhotoLink ? deviceData.carPhotoLink  : '/static/images/index/bike.png'"
						mode="heightFix">
					</image>
					<!-- 		<u--image
							:src="deviceData.carPhotoLink ? deviceData.carPhotoLink  : '/static/images/index/bike.png'"
							width="300px;" mode="heightFix"></u--image> -->

				</view>
			</view>
			<view class="p30">
				<view class="card-shadow-box plr30tb20">
					<slide-unlock :labelClass="indexDataPoint.lockStatus == 1 ? 'c-primary' : ''"
						:label="indexDataPoint.lockStatus == 1 ? '已开锁' : '滑动开锁'" ref="slideUnlock"
						@result="handleSlideResult">
					</slide-unlock>
				</view>
			</view>
			<view class="p30">
				<text class="bold f36">常用功能</text>
				<view class="mt30 flex-wrap">
					<view class="wper50">
						<card-box title="车辆定位" icon="/static/images/index/index-1.png" icon-color="#0099CC"
							@click="navigateToByAuth('/pagesHome/views/location',true,'location')"></card-box>
					</view>

					<view class="wper50 ml30">
						<card-box title="驾驶模式" icon="/static/images/index/index-5.png" icon-color="#0099CC"
							@click="navigateToByAuth('/pagesHome/views/driving')"></card-box>
					</view>
				</view>
				<view class="mt30 flex-wrap">
					<view class="wper50">
						<card-box title="电子围栏" icon="/static/images/index/index-3.png" icon-color="#0099CC"
							@click="navigateToByAuth('/pagesHome/views/fense',true,'fense')"></card-box>
					</view>
					<view class="wper50 ml30">
						<card-box title="骑行记录" icon="/static/images/index/index-4.png" icon-color="#0099CC"
							@click="navigateToByAuth('/pagesHome/views/trackList')"></card-box>
					</view>
				</view>
				<view class="mt30 flex-wrap">
					<view class="wper50">
						<card-box title="紧急防盗" icon="/static/images/index/index-2.png" icon-color="#0099CC"
							@click="navigateToByAuth('/pagesHome/views/guard')"></card-box>
					</view>
					<view class="wper50 ml30 test">
						<card-box title="震动防护" icon="/static/images/index/index-6.png" icon-color="#0099CC"
							@click="navigateToByAuth('/pagesHome/views/shakeProtect')"></card-box>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>



<script>
	import custEmpty from "@/components/cust-empty/index.vue";
	import CardBox from "@/components/card-box";
	import SlideUnlock from "@/components/slide-unlock";
	import {
		startOperateBluetooth,
	} from "@/static/bluetooth/core.js"
	import SlideLock from "../../../components/slide-lock";
	import {
		getBluetoothOrderAPI,
		parseBluetoothOrderAPI
	} from "@/api/api/communicate.js"
	import {
		verifyCarAPI,
		saveLogAPI
	} from "@/api/api/car.js"
	import {
		getRangeVal,
		throttle,
		getDifferenceDay
	} from "@/utils/utils";
	import {
		getStoreSyncUtil
	} from "@/utils/store.js"
	let bluetoothResponsePackage = '';
	let ser = '';
	import {
		mapState
	} from 'vuex'
	export default {
		components: {
			SlideLock,
			CardBox,
			SlideUnlock,
			custEmpty,
		},
		computed: {
			...mapState(["enduranceMileage", "unReadNum", "deviceData", "indexDataPoint", "respondPackage", "isConnected",
				"weather", "loginUser","isProduct"
			])
		},
		onShow() {
			this.$store.commit("setIsToIndex", false);
			if (this.unReadNum == 0) {
				uni.removeTabBarBadge({
					index: 3,
				})
			} else {
				uni.setTabBarBadge({
					index: 3,
					text: this.unReadNum + ''
				})
			}
			this.numerRound(0);
			if(this.isProduct){
				this.gotoAuthDialog();
			}
			this.gotoSubscribeDialog();
		},
		watch: {
			"unReadNum": {
				handler(unReadNum) {
					if (this.unReadNum == 0) {
						uni.removeTabBarBadge({
							index: 3,
						})
					} else {
						uni.setTabBarBadge({
							index: 3,
							text: this.unReadNum + ''
						})
					}
				}
			}
		},
		onLoad() {
			if (!this.$validatenull(this.deviceData.tboxExpireTime)) {
				let expireTip1 = getStoreSyncUtil("showExpireTip1");
				let expireTip7 = getStoreSyncUtil("showExpireTip7");
				let expireTip15 = getStoreSyncUtil("showExpireTip15");
				let showExpireTip1 = this.$validatenull(expireTip1[this.deviceData.id]) ? true : expireTip1[this.deviceData
					.id];
				let showExpireTip7 = this.$validatenull(expireTip7[this.deviceData.id]) ? true : expireTip7[this.deviceData
					.id];
				let showExpireTip15 = this.$validatenull(expireTip15[this.deviceData.id]) ? true : expireTip15[this
					.deviceData.id];
				let differenceDay = getDifferenceDay(this.deviceData.tboxExpireTime);
				// let differenceDay=getDifferenceDay("2023-3-13 00:00:00");
				if ((differenceDay == 0 && showExpireTip1) || (differenceDay == 7 && showExpireTip7) || (differenceDay ==
						15 && showExpireTip15)) {
					if (differenceDay == 0 && showExpireTip1) {
						expireTip1[this.deviceData.id] = false;
						uni.setStorageSync("showExpireTip1", expireTip1);
					} else if (differenceDay == 7 && showExpireTip7) {
						expireTip7[this.deviceData.id] = false;
						uni.setStorageSync("showExpireTip7", expireTip7);
					} else if (differenceDay == 15 && showExpireTip15) {
						expireTip15[this.deviceData.id] = false;
						uni.setStorageSync("showExpireTip15", expireTip15);
					}
					this.$showModal("您的服务订阅有效期还剩余" + differenceDay + "天，为不影响您的使用，请尽快订阅");
				}
			}
		},
		data() {
			return {
				isHasModal: false,
				lt: "<30"
			}
		},
		methods: {
			gotoAuthDialog() {

				if (this.deviceData.isAuth == "1" && !this.isHasModal) {
					let that = this;
					this.isHasModal = true;
					uni.showModal({
						title: '提示',
						content: "当前车辆未认证,如已认证,请5分钟后重新进入小程序",
						showCancel: true,
						cancelText: "退出",
						confirmText: "去认证",
						success(res) {
							if (res.confirm) {
								that.isHasModal = false;
								that.$navigateTo("/pagesMy/views/myMotorbike");
							} else if (res.cancel) {
								that.isHasModal = false;
								wx.exitMiniProgram({
									success(res) {
										console.log(JSON.stringify(res));
									},
									fail(res) {
										console.log(
											`exitMiniProgram fail: ${JSON.stringify(res)}`);
									}
								});

							}
						}
					});
				}
			},
			gotoSubscribeDialog() {
				if (!this.$validatenull(this.deviceData.tboxExpireTime) && !this.isHasModal) {
					let that = this;
					this.isHasModal = true;
					let differenceDay = getDifferenceDay(this.deviceData.tboxExpireTime);
					if (differenceDay < 0) {
						uni.showModal({
							title: '提示',
							content: "当前服务已到期，请前往-我的-服务订阅进行订阅",
							showCancel: true,
							cancelText: "退出",
							confirmText: "去订阅",
							success(res) {
								if (res.confirm) {
									that.isHasModal = false;
									that.$switchTab("/pages/views/home/userConfig");
								} else if (res.cancel) {
									that.isHasModal = false;
									wx.exitMiniProgram({
										success(res) {
											console.log(JSON.stringify(res));
										},
										fail(res) {
											console.log(
												`exitMiniProgram fail: ${JSON.stringify(res)}`
											);
										}
									});
								}
							}
						});
					}
				}
			},
			parsePacketCallback(flag) {
				//改变状态
				this.$store.commit("setIndexDataPoint", {
					...this.indexDataPoint,
					lockStatus: flag ? 1 : 0
				});
				uni.hideLoading();
				uni.showToast({
					title: flag ? "操作成功" : "操作失败",
					icon: 'none',
					mask: true
				})
				this.$nextTick(() => {
					this.$refs.slideUnlock.reset();
				})
				if (flag) {
					let params = {
						logType: 6,
						customerId: this.loginUser.user_id,
						cardId: this.deviceData.id,
						businessId: this.deviceData.id,
						carName: this.deviceData.nickName,
						logAssort: 2,
						content: "开锁"
					};
					saveLogAPI(params)
				}
			},
			navigateToByAuth: throttle(function(url, isTab = false, mode) {
				// if(this.deviceData.isAuth =="1"){
				// 	this.$showModal("当前车辆未认证，前往认证",()=>{
				// 		this.gotoAuth(this.deviceData);
				// 	},true);
				// }else{
				if (isTab) {
					this.$store.commit("setMapMode", mode);
					this.$navigateTo(url);
				} else {
					this.$navigateTo(url);
				}
				//}
			}),
			//去认证
			gotoAuth(item) {
				this.$store.commit("setSpecialAppOnShow", true);
				if (item.isAuth == "1") {
					verifyCarAPI(item.id).then(([err, data]) => {
						if (err) return;
						let resData = JSON.parse(data);
						this.$store.commit("setVerifyUrl", resData.url)
						this.$reLaunch(`/pages/views/home/verify`)
					})
				}
			},
			$switchTab(url) {
				uni.switchTab({
					url: url
				});
			},
			getBluetoothOrderAPIFun(callback = () => {}) {
				getBluetoothOrderAPI({
					deviceId: this.deviceData.id,
					commandCode: "OPEN_LOCK_CAR"
				}).then(([err, data]) => {
					if (err) return;
					callback(data);
				})
			},

			// 开锁
			handleSlideResult(e) {
				if (!e.flag) {
					return;
				}
				if (this.isConnected) {
					startOperateBluetooth("开锁中", 1005, this.parsePacketCallback, () => {
						this.$nextTick(() => {
							this.$refs.slideUnlock.reset();
						}, )
					});
				} else {
					uni.showToast({
						title: "蓝牙未连接",
						icon: 'none',
						mask: true
					})
					this.$nextTick(() => {
						this.$refs.slideUnlock.reset();
					})

				}

			},
			numerRound(val) {
				let str = val + '';
				let lastNumber = parseInt(str.substring(str.length - 1));
				if (lastNumber < 5) {
					if (str.length > 1) {
						return parseInt(str.substring(0, str.length - 1) + "0");
					} else {
						return 0;
					}
				} else {
					if (str.length > 1) {
						return parseInt(str.substring(0, str.length - 1)) * 10 + 10;
					} else {
						return 10;
					}
				}
			},
			setNumerRound(val, arr, fix = 2) {
				let newval = this.toFormatVal(val, arr, fix);
				if (newval != '-') {
					return this.numerRound(newval);
				} else {
					return "-";
				}
			},
			/** 将数据转为在有效数据范围且小数固定位数的数据
			 * @param {Object} val
			 * @param {Object} arr
			 * @param {Object} fix
			 */
			toFormatVal(val, arr, fix = 2) {
				if (val == null || val === '') {
					return '-'
				}
				let n = getRangeVal(val, arr);
				return Number(n).toFixed(fix);
			}
		}
	}
</script>

<style scoped>


</style>
